from sklearn.decomposition import PCA
import torch
import torch.nn as nn

# 模拟 CLIP 特征
features = torch.randn(1000, 512).numpy()  # 转为 NumPy 进行 PCA
target_dim = 128

# PCA 降维
pca = PCA(n_components=target_dim)
reduced_features = pca.fit_transform(features)

# 转回 Tensor
reduced_features = torch.tensor(reduced_features)

print(f"PCA 降维后形状: {reduced_features.shape}")

class ConvReducer(nn.Module):
    def __init__(self, outputs):
        super(ConvReducer, self).__init__()
        self.conv = nn.Conv1d(1, 1, kernel_size=5)  # 1D 卷积
        self.adapt = nn.AdaptiveAvgPool1d(outputs)
        
    def forward(self, x):
        # 假设输入形状为 [batch, seq_len, input_dim]
        x = x.reshape(x.shape[0], 1, -1)  # 扩展为 [batch, 1, input_dim]
        x = self.conv(x)  # [batch, target_dim, input_dim]
        x = self.adapt(x)
        return x.reshape(x.shape[0], -1)  # [batch, target_dim]

# 使用示例
input_dim = 1
target_dim = 1

conv_reducer = ConvReducer(300)
clip_features = torch.randn(512, 512)  # [batch, 512]
reduced_features = conv_reducer(clip_features)  # [batch, 300]
print(reduced_features.shape)
